package yxy.game.pm2.command.soloride;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.SoloRideMessage;
import yxy.game.pm2.module.soloride.SoloRideHandle;
import yxy.game.pm2.module.soloride.SoloRideModule;

import java.util.Collection;

/** 千里走单骑 千里走单骑战斗开始 */
@MessageType(proto = Command.SoloRideChanllengeExecute, classtype = SoloRideMessage.SoloRideChanllengeExecuteRequest.class)
public class CMD_SoloRideChanllengeExecute extends Command<SoloRideMessage.SoloRideChanllengeExecuteRequest> {

	@Override
	public void execute(MessageSource messageSource, SoloRideMessage.SoloRideChanllengeExecuteRequest request) {
		String playerCode = messageSource.getTag();
		String heroCode = request.getHero();

		SoloRideMessage.SoloRideChanllengeExecuteResponse.Builder response = SoloRideMessage.SoloRideChanllengeExecuteResponse.newBuilder();

		SoloRideModule soloRideModule = SoloRideModule.get(playerCode);
		if (soloRideModule == null) {
			send(messageSource, response, Result.ModuleNotOpen);// 模块没开启
			return;
		}

		try {
			if (soloRideModule.tryLock() && Hero.lockHero(playerCode)) {
				Hero hero = Hero.get(playerCode, heroCode);
				if (hero == null) {
					send(messageSource, response, Result.ParamError);// 所选武将不存在
				}

				SoloRideHandle handle = new SoloRideHandle();

				Collection<SoloRideMessage.SoloRideBattle> resps = handle.battleResponseExecute(playerCode, hero);
				if (resps == null) {
					send(messageSource, response, Result.ParamError);
					return;
				}
				soloRideModule = SoloRideModule.get(playerCode);

				response.addAllBattleResp(resps);
				response.setBest(soloRideModule.getBest());
				response.addAllBox(soloRideModule.rewardBox());
				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			soloRideModule.unlock();
			Hero.unlockHero(playerCode);
		}

	}

	private void send(MessageSource messageSource, SoloRideMessage.SoloRideChanllengeExecuteResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}